import contact from "@/assets/contact.png";
import BackTile from "@/components/BackTitle";
import ListItem from "@/components/ListItem";
import Loading from "@/components/Loading";
import {
	getStorageSync,
	removeStorageSync,
	show,
	switchTab
} from "@/utils/common";
import { taroLogin } from "@/utils/taroUtils";
import { Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { connect } from "react-redux";
import "./index.scss";

function Mine(props) {
  const { phone, isLogin } = props;
  const token = getStorageSync("token");

  const login = () => {
    props.dispatch({ type: "user_updateState", data: { isLogin: true } });
  };

  const register = (openid) => {
    props.dispatch({ type: "global_updateState", data: { loading: true } });
    props.dispatch({ type: "user_updateState", data: { openid } });
  };
  const onAuth = () => {
    taroLogin(register, login);
  };

  const handleClick = (type) => {
    if (!token) {
      show("请先登录！");
      switchTab("/pages/mine/index");
      return;
    }
    if (type == "contact") {
      Taro.makePhoneCall({
        phoneNumber: "400-9999",
      });
    } else if (type == "logout") {
      removeStorageSync("token");
      props.dispatch({
        type: "user_reset",
      });
      show("退出成功");
    }
  };

  return (
    <View>
      <Loading />
      <View className="center-top">
        <BackTile title="个人中心" left={false} type="white" />
        <View className="center-top-wrapper">
          {token && isLogin ? (
            <View className="center-user">
              用户：<Text style={{ marginLeft: 3 }}>{phone}</Text>
            </View>
          ) : (
            <View className="center-user" onClick={onAuth}>
              登录/注册
            </View>
          )}
        </View>
      </View>
      <View className="center-bottom">
        <View className="center-bottom-wrapper">
          <ListItem
            onClick={() => handleClick("contact")}
            iconUrl={contact}
            title="联系客服"
            extraText="400-999"
          />
        </View>
      </View>
    </View>
  );
}

export default connect(
  ({ user }) => {
    const { phone, isLogin, username } = user;
    return { phone, isLogin, username };
  },
  null,
  null,
  { forwardRef: true }
)(Mine);
